﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace LayeredArchitectureSample.Infrastructure
{
    public static class Reflection
    {
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
        {
            if (propertyExpression == null) throw new ArgumentNullException("propertyExpression");

            var propertyBodyAsMemberExpression = propertyExpression.Body as MemberExpression;

            if (propertyBodyAsMemberExpression == null)
            {
                throw CreateArgumentException();
            }

            var propertyInfo = propertyBodyAsMemberExpression.Member as PropertyInfo;

            if (propertyInfo == null)
            {
                throw CreateArgumentException();
            }

            var propertyName = propertyInfo.Name;

            return propertyName;
        }

        private static ArgumentException CreateArgumentException()
        {
            return new ArgumentException("Lambda-expression must point to a property");
        }
    }
}